package com.lilosoft.business.precity.service;

import com.lilosoft.business.cga.dao.IdCardInfoMapper;
import com.lilosoft.business.cga.models.*;
import com.lilosoft.business.precity.dao.UpProAcceptMapper;
import com.lilosoft.business.precity.models.UpProAccept;
import com.lilosoft.business.precity.models.UpProAcceptExample;
import com.lilosoft.business.util.IDCard;
import com.lilosoft.business.util.PreInitCdBatchUtil;
import com.lilosoft.core.utils.StringUtils;
import com.lilosoft.core.utils.commons.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 办件受理信息
 * User: 小峰
 * Date: 2019-08-27
 * Time: 17:49
 */
@Service
public class UpProAcceptService {

    private Logger logger = LoggerFactory.getLogger(UpProAcceptService.class);

    @Autowired
    private UpProAcceptMapper upProAcceptMapper;
    @Autowired
    private PreInitCdBatchUtil preInitCdBatchUtil;
    @Autowired
    private IdCardInfoMapper idCardInfoMapper;

    /**
     * 同步办件受理信息
     *
     * @param cgaCase
     * @param egsProject
     * @param egsProjectsummary
     * @param cgaPerson
     * @param sysDept
     * @return
     */
    public UpProAccept upProAcceptSynchronous(CgaCase cgaCase, EgsProject egsProject, EgsProjectsummary egsProjectsummary,
                                              CgaCaseRelatedPerson cgaPerson, SysDept sysDept, TemporaryProject temporaryProject) {
        UpProAccept upProAccept = new UpProAccept();
        upProAccept.setRowguid(UUIDUtils.createUUId());
        upProAccept.setProjectno("05" + cgaCase.getCaseId());
        upProAccept.setTaskname(cgaCase.getProjectName());


        upProAccept.setCatalogcode(temporaryProject.getCatalogcode());
        upProAccept.setTaskcode(temporaryProject.getTaskcode());
        upProAccept.setTasktype(temporaryProject.getTasktype());
        upProAccept.setTaskversion(StringUtils.toInteger(temporaryProject.getTaskversion()));
        upProAccept.setTaskhandleitem(temporaryProject.getTaskhandleitem());
        upProAccept.setOrgcode(temporaryProject.getOrgcode());
        upProAccept.setOrgname(temporaryProject.getOrgname());

        //upProAccept.setOrgcode(sysDept.getDeptCode());
        //upProAccept.setOrgname(sysDept.getSimplyName());
        //upProAccept.setTaskcode(cgaCase.getProjectNo());
        //upProAccept.setTaskversion(egsProject.getVersion());
        /*switch (egsProject.getProjectType()) {
            case "01":
                upProAccept.setTasktype("01");
                break;
            case "07":
                upProAccept.setTasktype("02");
                break;
            case "05":
                upProAccept.setTasktype("03");
                break;
            case "04":
                upProAccept.setTasktype("04");
                break;
            case "09":
                upProAccept.setTasktype("05");
                break;
            case "02":
                upProAccept.setTasktype("06");
                break;
            case "10":
                upProAccept.setTasktype("07");
                break;
            case "42":
                upProAccept.setTasktype("08");
                break;
            case "08":
                upProAccept.setTasktype("09");
                break;
            case "03":
                upProAccept.setTasktype("10");
                break;
            case "06":
                upProAccept.setTasktype("11");
                break;
            case "30":
                upProAccept.setTasktype("12");
                break;
            case "41":
                upProAccept.setTasktype("13");
                break;
            default:
                break;
        }*/

        String ISFIXEDASSETS = egsProjectsummary.getIsFixedAssets();
        upProAccept.setIsfixedassets("0".equals(ISFIXEDASSETS) ? "1" : "0");

        upProAccept.setApplytype("01".equals(egsProject.getDealType()) ? "1" : "2");
        upProAccept.setProjecttype("02".equals(egsProject.getCaseType()) ? "2" : "1");

        if (StringUtils.isEmpty(cgaCase.getApplySource())) {
            upProAccept.setTransactionSource(31);
        } else {
            switch (cgaCase.getApplySource()) {
                case "01":
                    upProAccept.setTransactionSource(11);
                    break;
                case "06":
                    upProAccept.setTransactionSource(22);
                    break;
                case "04":
                    upProAccept.setTransactionSource(13);
                    break;
                default:
                    upProAccept.setTransactionSource(31);
                    break;
            }
        }

        if (StringUtils.isEmpty(cgaCase.getCaseState())) {
            upProAccept.setTransactionState(20);
        } else {
            switch (cgaCase.getCaseState()) {
                case "04":
                    upProAccept.setTransactionState(31);
                    break;
                case "09":
                    upProAccept.setTransactionState(45);
                    break;
                case "13":
                    upProAccept.setTransactionState(43);
                    break;
                case "12":
                    upProAccept.setTransactionState(42);
                    break;
                default:
                    upProAccept.setTransactionState(20);
                    break;
            }
        }

        //根据事项的服务类型判断办件的申请人类型
        if (temporaryProject.getServiceType().contains("02")) {
            upProAccept.setApplyertype("1");//自然人
        } else {
            upProAccept.setApplyertype("2");//企业
        }
        //验证申请人证件类型，及申请人证件号
        if (!invalidApplyerpagetype(upProAccept, cgaCase, cgaPerson,temporaryProject)) {
            return null;
        }
        upProAccept.setApplyername(cgaCase.getAcceptUserName() == null ? "默认申请人" : cgaCase.getAcceptUserName());

        invalidDate(cgaCase);
        upProAccept.setApplydate(cgaCase.getRegisterTime());    //申请
        upProAccept.setAcceptdate(cgaCase.getAcceptTime());     //受理
        upProAccept.setConcludedDate(cgaCase.getEndTime()); //办结
        upProAccept.setIsFee("0");

        upProAccept.setCheckState(0);
        upProAccept.setAdministrativeDiv("05");
        upProAccept.setCdUptime(new Date());
        upProAccept.setDelState(0);
        upProAccept.setSyncSign(0);
        upProAccept.setCdBatch(preInitCdBatchUtil.initCdBatch());
        upProAccept.setDatasource("105");

        List<UpProAccept> upProAccepts = selectByProjectNo(upProAccept.getProjectno());
        if (null == upProAccepts || upProAccepts.size() <= 0) {
            upProAcceptMapper.insertSelective(upProAccept);
        } else {
            return null;
        }
        return upProAccept;
    }


    public List<UpProAccept> selectByProjectNo(String projectNo) {
        UpProAcceptExample example = new UpProAcceptExample();
        UpProAcceptExample.Criteria criteria = example.createCriteria();
        criteria.andProjectnoEqualTo(projectNo);
        criteria.andDelStateEqualTo(0);
        return upProAcceptMapper.selectByExample(example);
    }

    /**
     * 验证申请人证件类型，及申请人证件号
     *
     * @param upProAccept
     * @param cgaCase
     * @param cgaPerson
     * @return
     */
    public boolean invalidApplyerpagetype(UpProAccept upProAccept, CgaCase cgaCase, CgaCaseRelatedPerson cgaPerson, TemporaryProject temporaryProject) {
        String number = StringUtils.isEmpty(cgaPerson.getCardNumber()) ? StringUtils.isEmpty(cgaPerson.getKeymanIdcard()) ? cgaPerson.getJbrCardNumber() : cgaPerson.getKeymanIdcard() : cgaPerson.getCardNumber();
        if (StringUtils.isEmpty(number)) {
            if (StringUtils.isNotEmpty(cgaCase.getCallSignBusinessCode())) {   //根据Q码查
                //logger.warn("根据Q码查询身份证号,CaseId:"+cgaCase.getCaseId() +" | Q码:"+ cgaCase.getCallSignBusinessCode());
                number = idCardInfoMapper.getCardByQcodeToNumberTanking(cgaCase.getCallSignBusinessCode().substring(1));
            }
//            else {
//                if (StringUtils.isEmpty(upProAccept.getApplyerpagecode())) {
//                    //logger.warn("根据姓名查询身份证号,CaseId:"+cgaCase.getCaseId() +" | 姓名:"+ cgaPerson.getRelatedPersonName());
//                    number = idCardInfoMapper.getCardByNameToPrmIdCard(cgaPerson.getRelatedPersonName());
//                }
//            }
        }


        if (StringUtils.isEmpty(number)) {
            upProAccept.setApplyerpagetype("999");
            upProAccept.setApplyerpagecode("朝阳区默认编码");
        } else {
            if (StringUtils.isNotEmpty(IDCard.IdentityCardVerification(number))) {
                if("02".equals(temporaryProject.getServiceType())){
                    upProAccept.setApplyerpagetype("999");
                }else{
                    upProAccept.setApplyerpagetype("001"); //统一社会信用代码证
                    upProAccept.setApplyertype("2");//企业
                }
            } else {
                upProAccept.setApplyerpagetype("111"); //居民身份证
            }
            upProAccept.setApplyerpagecode(number);
        }
        return true;
    }

    /**
     * 验证 申请时间，受理时间，结果时间
     *
     * @param cgaCase
     */
    public void invalidDate(CgaCase cgaCase) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -2);
        if (null == cgaCase.getRegisterTime()) {  //申请时间
            cgaCase.setRegisterTime(calendar.getTime());
        }
        if (null == cgaCase.getAcceptTime()) { //受理时间
            calendar.setTime(cgaCase.getRegisterTime());
            calendar.add(Calendar.DATE, 1);
            cgaCase.setAcceptTime(calendar.getTime());
        }
        if (null == cgaCase.getEndTime()) { //办结时间
            calendar.setTime(cgaCase.getAcceptTime());
            calendar.add(Calendar.DATE, 1);
            cgaCase.setEndTime(calendar.getTime());
        }


        if (cgaCase.getAcceptTime().getTime()-cgaCase.getRegisterTime().getTime()<=1000) {
            Date accetp = cgaCase.getAcceptTime();
            calendar.setTime(accetp);
            calendar.add(Calendar.DATE, -1);
            cgaCase.setAcceptTime(cgaCase.getRegisterTime());
            cgaCase.setRegisterTime(calendar.getTime());
        }

        if(cgaCase.getEndTime().getTime()-cgaCase.getAcceptTime().getTime()<=1000){
            Date endtime=cgaCase.getEndTime();
            calendar.setTime(endtime);
            calendar.add(Calendar.HOUR,-2);
            cgaCase.setEndTime(cgaCase.getAcceptTime());
            cgaCase.setAcceptTime(calendar.getTime());
        }

        if(cgaCase.getAcceptTime().getTime()-cgaCase.getRegisterTime().getTime()>1000 &&  cgaCase.getEndTime().getTime()-cgaCase.getAcceptTime().getTime()>1000){
            return;
        }else{
            invalidDate(cgaCase);
        }


    }

    /**
     * 根据cdBatch 统计数据个数（办件受理信息）
     *
     * @param cdBatch
     * @return
     */
    public Long countByCDbatch(String cdBatch) {
        UpProAcceptExample example = new UpProAcceptExample();
        UpProAcceptExample.Criteria criteria = example.createCriteria();
        criteria.andCdBatchEqualTo(cdBatch);
        return upProAcceptMapper.countByExample(example);
    }

}
